/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.saber.certificacao.beansjsf.conversores;

import br.com.saber.certificacao.ejbs.stateless.interfaces.CertificacaoBeanLocal;
import br.com.saber.certificacao.modelos.Certificacao;
import br.com.saber.certificacao.utils.UtilMetodos;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.commons.lang.StringUtils;

/**
 *
 * @author gbvbahia
 */
@FacesConverter(value = "certificacaoConverter")
public class CertificacaoConverter implements Converter {

    CertificacaoBeanLocal certificacaoBean = lookupCertificacaoBeanLocal();

    @Override
    public Object getAsObject(FacesContext fc, UIComponent uic, String string) throws ConverterException {
        if (StringUtils.isBlank(string)) {
            return string;
        }
        Certificacao certificacao = certificacaoBean.buscarCertificacaoPorNome(string);
        if (certificacao == null) {
            exception(fc);
        }
        return certificacao;
    }

    @Override
    public String getAsString(FacesContext fc, UIComponent uic, Object o) throws ConverterException {
        if (o == null) {
            return null;
        } else if (o.toString().equals("")) {
            return "";
        } else if (o instanceof String) {
            return o.toString();
        }
        try {
            Certificacao certificacao = (Certificacao) o;
            return certificacao.getNome().toString();
        } catch (ClassCastException e) {
            exception(fc);
        }
        return o.toString();
    }

    private void exception(FacesContext fc) {
        FacesMessage msg = new FacesMessage(UtilMetodos.getResourceBundle("erroconvertererro", fc));
        msg.setSeverity(FacesMessage.SEVERITY_FATAL);
        throw new ConverterException(msg);
    }

    private CertificacaoBeanLocal lookupCertificacaoBeanLocal() {
        try {
            Context c = new InitialContext();
            return (CertificacaoBeanLocal) c.lookup("java:global/Saber/saber-ejb/CertificacaoBean!br.com.saber.certificacao.ejbs.stateless.interfaces.CertificacaoBeanLocal");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }
}
